# audio_player.py
import os
import sys
import pygame

# 初始化 pygame mixer
try:
    pygame.mixer.init()
    HAS_PYGAME = True
except ImportError:
    HAS_PYGAME = False
    print("⚠️ pygame 未安装，将使用系统提示音。安装命令：pip install pygame")


def play_alarm_sound(sound_file=None):
    """
    播放闹钟铃声
    :param sound_file: 音频文件路径，支持 mp3/wav/ogg
    :return: 是否成功播放文件
    """
    if HAS_PYGAME and sound_file and os.path.exists(sound_file):
        try:
            pygame.mixer.music.stop()
            pygame.mixer.music.load(sound_file)
            pygame.mixer.music.play()
            print(f"🔊 正在播放铃声: {sound_file}")
            return True
        except Exception as e:
            print(f"播放失败 {sound_file}: {e}")

    # 降级使用系统提示音
    fallback_beep()
    return False


def fallback_beep():
    """系统提示音备用方案"""
    try:
        if sys.platform.startswith('win'):
            import winsound
            winsound.Beep(1000, 1000)  # 1秒蜂鸣
        elif sys.platform.startswith('darwin'):  # macOS
            os.system('afplay /System/Library/Sounds/Glass.aiff')
        else:  # Linux
            os.system('beep -f 1000 -l 1000 2>/dev/null || paplay /usr/share/sounds/gnome/default/alerts/bark.ogg 2>/dev/null')
    except Exception as e:
        print("系统提示音失败:", e)